﻿using Common;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;

namespace IntelligentFiles.HcCommon
{
    /// <summary>
    /// http接口操作类
    /// </summary>
    class HttpApi
    {

        #region 《通用接口》
        /// <summary>
        /// 错误标识
        /// </summary>
        public const string REEOR = "ERROR";
        /// <summary>
        /// 获取数据接口
        /// </summary>
        /// <param name="url"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public static string httpGet(string url, string param)
        {
            try
            {
                UTF8Encoding encoding = new UTF8Encoding();
                byte[] data = encoding.GetBytes(param);
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
                request.Method = "GET";
                request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
                // request.ContentLength = data.Length;
                request.Timeout = 5000;
                //request.ServicePoint.Expect100Continue = false; 
                Stream newStream = request.GetRequestStream();
                // Send the data.  
                newStream.Write(data, 0, data.Length);
                newStream.Close();
                // Get response  
                WebResponse response = request.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                string result = reader.ReadToEnd().Replace("null", "");
                //日志
                CommonApi.writeLog("数据获取接口成功:" + result);

                return result;
            }
            catch (Exception ex)
            {
                //记录错误日志
               CommonApi.writeLog("数据获取接口异常:" + ex.ToString());

                return REEOR;
            }
        }
        
        /// <summary>
        /// post数据提交接口
        /// </summary>
        /// <param name="url">地址</param>
        /// <param name="param">参数</param>
        /// <returns></returns>
        public static string httpPost(string url, string param)
        {
            try
            {
                UTF8Encoding encoding = new UTF8Encoding();
                byte[] data = encoding.GetBytes(param);
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
                // request.ContentLength = data.Length;
                request.Timeout = 5000;

                //request.ServicePoint.Expect100Continue = false; 
                Stream newStream = request.GetRequestStream();
                // Send the data.  
                newStream.Write(data, 0, data.Length);
                newStream.Close();
                // Get response  
                WebResponse response = request.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                string result = reader.ReadToEnd().Replace("null", "");
                //日志
                CommonApi.writeLog("数据提交接口成功:" + result);

                return result;
            }
            catch (Exception ex)
            {
                //记录错误日志
                CommonApi.writeLog("数据提交接口异常:" + ex.ToString());
                return REEOR;
            }

        }
 #endregion
        #region 《数据接口》
        /// <summary>
        /// 登录验证
        /// </summary>
        /// <param name="user"></param>
        /// <param name="pwd"></param>
        public static void login(string user,string pwd)
        {
            try
            {
                //数据组装
                JsonInfo.loginInfo info = new JsonInfo.loginInfo();
                info.user = user;
                info.pwd = pwd;
                //数据转化json
                //转化
                string jsonData = getJsonByObject(info);
                if (jsonData != REEOR)
                {
                    CommonApi.writeLog("登录验证信息，" + jsonData);
                    //上传
                    httpPost(URL.loginUrl, jsonData);
                }

            }
            catch(Exception  ex)
            {
                CommonApi.writeLog("登录验证异常,"+ex.ToString());
            }
        }
        #endregion
        #region《Json转化》
        /// <summary>
        /// object转json
        /// 用于将对象实例转化成参数json结构
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string getJsonByObject(Object obj)
        {
            try
            {
                //实例化DataContractJsonSerializer对象，需要待序列化的对象类型
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
                //实例化一个内存流，用于存放序列化后的数据
                MemoryStream stream = new MemoryStream();
                //使用WriteObject序列化对象
                serializer.WriteObject(stream, obj);
                //写入内存流中
                byte[] dataBytes = new byte[stream.Length];
                stream.Position = 0;
                stream.Read(dataBytes, 0, (int)stream.Length);
                //通过UTF8格式转换为字符串
                return Encoding.UTF8.GetString(dataBytes);
            }
            catch (Exception ex)
            {
                //错误日志
                CommonApi.writeLog("JSON转化异常:" + ex.ToString());
                return REEOR;
            }

        }
        #endregion
    }
}
